package es.seam.myebay;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import es.seam.myebay.model.User;
import es.seam.myebay.util.Hash;
import es.seam.myebay.util.Navigator;

@Name("authenticator")
public class Authenticator {
    
    @Logger
    private Log log;

    /**
     * Exportamos el usuario logueado a la sesion bajo el nombre 'currentUser'
     */
    @Out(required = false, scope = ScopeType.SESSION, value = "currentUser")
    private User user;
    
    @In
    private Credentials credentials;

    @In
    private EntityManager entityManager;
    
    @In(value = "hashUtil")
    private Hash hash;
    
    public boolean authenticate() {
        log.info("authentificando {0}", credentials.getUsername());
        
        // Asignamos el valor a this.user para que sea outjectado
        this.user = this.getUserFromCredentials(credentials.getUsername(), credentials.getPassword());
        
        // TODO Anadir roles al componente identity
        return user != null;
    }
    
    public User getUserFromCredentials(String username, String password) {
        User user = null;
        String ejbql = "SELECT u FROM User u where u.username = :username and password = :password";
        Query query = entityManager.createQuery(ejbql);
        query = query.setParameter("username", credentials.getUsername());
        query = query.setParameter("password", hash.hash(password));
        try {
            user = (User) query.getSingleResult();
        } catch (NoResultException nre) {
            log.info("error autentificando el usuario #0", username);
        } catch (Exception e) {
            log.error("error insesperado", e.getCause());
            e.printStackTrace();
        }
        return user;
    }
    
    public String logout() {
        Identity.instance().logout();
        Contexts.removeFromAllContexts("currentUser");
        return Navigator.SUCCESS;
    }
}
